﻿using FastBuild.TimeJob;
using Wechat_PublicNumber.Common;
using Wechat_PublicNumber.Entity;
using Wechat_PublicNumber.Model;
using Wechat_PublicNumber.Repository;
using Wechat_PublicNumber.SettingModel;

namespace Wechat_PublicNumber.Jobs
{
    /// <summary>
    /// 每日天气预报
    /// </summary>
    [SkipWhileExecuting]
    public class ToDoListReminderJob : DataAccess, IJob
    {
        #region DI
        [Autowired]
        private WxHttpInvoke _wxHttpInvoke;

        [Autowired]
        private WxTemplateRepository _templateRepository;

        [Autowired]
        private WxSetting _wxSetting;

        #endregion

        public async Task Execute()
        {
            _logger.Info("ToDoListReminderJob Begin", "ToDoListReminderJob");

            var now = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd HH:mm"));

            var toDoList = await WXDb.Queryable<ToDoList>()
                .Where(s => s.ReminderTime == now && s.IsDone == false)
                .ToListAsync();

            foreach (var item in toDoList)
            {
                var pushData = await _templateRepository.GetTemplateData(WeChatTemplateEnum.CommonMessage, _wxSetting.AdminOpenID, new { Message = $"待办事项 “{item.Name}” 触发提醒，请尽快处理" });
                if (pushData is not null)
                    await _wxHttpInvoke.PushTemplate(pushData);
                item.IsDone = true;
            }

            await WXDb.Updateable(toDoList).ExecuteCommandAsync();

            _logger.Info($"ToDoListReminderJob End", "ToDoListReminderJob");
        }
    }
}
